package com.example.demo.service.impl;

import com.example.demo.entity.File;
import com.example.demo.entity.Folder;
import com.example.demo.exception.BusyException;
import com.example.demo.exception.file.InvalidNewpathException;
import com.example.demo.exception.file.InvalidPathException;
import com.example.demo.mapper.FileMapper;
import com.example.demo.mapper.FolderMapper;
import com.example.demo.service.FileService;
import com.example.demo.utils.*;
import com.jcraft.jsch.SftpException;
import com.lowagie.text.DocumentException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class FileServiceImpl implements FileService {

    @Resource
    FolderMapper folderMapper;
    @Resource
    FileMapper fileMapper;
//    @Resource
//    FolderService folderService;


    private FolderUtils folderUtils = new FolderUtils();
    private Word2HtmlUtils word2HtmlUtils=new Word2HtmlUtils();
    private Html2WordUtils html2WordUtils=new Html2WordUtils();
    private Md2pdfUtils md2pdfUtils=new Md2pdfUtils();
    private CompressImg compressImg=new CompressImg();
   // private FolderServiceImpl folderServiceImpl = new FolderServiceImpl();

    @Override
    public void updateFileLastTime(String path) throws InvalidPathException {
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(currentDate);
        int i = fileMapper.fileUpdateLastTime(time, path);
        if (i <= 0) {
            throw new InvalidPathException();
        }
    }

    @Override
    public void uploadFile(String path, MultipartFile file) throws Exception {
        //在磁盘上加入文件/图片
        String username = UserNameUtils.getUsername();
        String basePath = FolderUtils.basePath +"/"+username;
        String filename = file.getOriginalFilename();
        //String sshfilename=RandomPathUtils. getRandomName();
        folderUtils.uploadFile(basePath, path, filename, file);

        //在数据库中加入文件/图片，即要在folder表中加入，也要在file表中加入
        String tmp = username;
        String filePath = path + "/" + filename;
        String[] dirs = filePath.split("/");
        int size = dirs.length;
        for (int i = 0; i < size; i++) {
            tmp += "/" + dirs[i];
            Folder folder = folderMapper.selectFolderByPath(tmp);
            if (folder == null) {
                //如果该文件夹在文件夹表中不存在，则创建
                Folder fd = new Folder();
                fd.setPath(tmp);
                fd.setUsername(UserNameUtils.getUsername());
                folderMapper.insertFolder(fd);
            }
            //最后一个是文件路径
            if (i == size - 1) {
                File fl = fileMapper.selectFileByPath(tmp);
                if (fl == null) {
                    //如果数据库中没有该文件则新加入
                    saveFileToMysql(tmp, file, filename,"insert");
                }else{
                    //如果有则覆盖
                    saveFileToMysql(tmp,file,filename,"update");
                }
            }
        }
    }

    @Override
    public void fileAddStar(String path) throws InvalidPathException {
        //文件加星不涉及磁盘操作，直接在数据库中操作即可
        int i = fileMapper.fileAddStar(UserNameUtils.getUsername()+"/"+path);
        //更新上次修改时间
        updateFileLastTime(UserNameUtils.getUsername()+"/"+path);

        if (i <= 0) {
            throw new InvalidPathException();
        }

    }

    @Override
    public void fileCancelStar(String path) throws InvalidPathException {
        int i = fileMapper.fileCancelStar(UserNameUtils.getUsername()+"/"+path);
        //更新上次修改时间
        updateFileLastTime(UserNameUtils.getUsername()+"/"+path);
        if (i <= 0) {
            throw new InvalidPathException();
        }
    }

    @Override
    public void fileAddTop(String path) throws InvalidPathException {
        int i = fileMapper.fileAddTop(UserNameUtils.getUsername()+"/"+path);
        //更新上次修改时间
        updateFileLastTime(UserNameUtils.getUsername()+"/"+path);
        if (i <= 0) {
            throw new InvalidPathException();
        }
    }

    @Override
    public void fileCancelTop(String path) throws InvalidPathException {
        int i = fileMapper.fileCancelTop(UserNameUtils.getUsername()+"/"+path);
        //更新上次修改时间
        updateFileLastTime(UserNameUtils.getUsername()+"/"+path);
        if (i <= 0) {
            throw new InvalidPathException();
        }
    }

    @Override
    public Map<String, Object> getFileInfo(String path) throws InvalidPathException {
        Map<String, Object> file = fileMapper.getFileInfo(UserNameUtils.getUsername()+"/"+path);
        if (file == null) {
            throw new InvalidPathException();
        } else {
            file.putIfAbsent("author", null);
            file.putIfAbsent("origin", null);

            StringBuilder folder = new StringBuilder();
            String allpath = (String) file.get("path");
            String[] folders = allpath.split("/");
            //从1开始,因为不把用户名显示给前端/用户
            for (int i = 1; i < folders.length - 1; i++) {
                if (i == 1) {
                    folder.append(folders[i]);
                } else {
                    folder.append("/").append(folders[i]);
                }
            }
            file.put("folder", folder.toString());
            file.put("path",folder.toString()+"/"+folders[folders.length-1]);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = (Date) file.get("createDatetime");
            String str = sdf.format(date);
            file.put("createDatetime", str);

            date = (Date) file.get("lastUpdateDatetime");
            str = sdf.format(date);
            file.put("lastUpdateDatetime", str);

        }
        return file;
    }

    @Override
    public void renameFile(String oldPath, String newPath) throws InvalidPathException, SftpException {
        //在磁盘上修改文件名称
        String username = UserNameUtils.getUsername();
        File file = fileMapper.selectFileByPath(username+"/"+oldPath);
        Folder folder = folderMapper.selectFolderByPath(username+"/"+oldPath);
        String oldPathAll = FolderUtils.basePath+"/" + username + "/" + oldPath;
        String newPathAll = FolderUtils.basePath+"/" + username + "/" + newPath;
        int i = 1;
        if (folder == null) {
            throw new InvalidPathException();
        } else if (file == null) {
            //如果是修改文件夹名
            folderUtils.moveFolder(oldPathAll, newPathAll);
        } else {
            //修改文件名
            folderUtils.moveFile(oldPathAll, newPathAll);
        }
        //在数据库中修改(即修改路径)
        //找到全匹配的路径并且修改
        String sqlOldPath=username+"/"+oldPath;
        String sqlNewPath=username+"/"+newPath;
        folderMapper.renameFolderOnePath(sqlOldPath,sqlNewPath);
        //原路径后面加“/”，找到该路径下的文件并且修改
        sqlOldPath+="/";
        //sqlNewPath+="/";
        int len=sqlOldPath.length()+1;
        String[] temp = newPath.split("/");// 路径分段
        String newTitle = temp[temp.length - 1];// 取文件名
        folderMapper.updateFileOrFolderPath(sqlOldPath, sqlNewPath+"/", len);
        if(file!=null){
            //如果是重命名文件，则还需要修改标题
            fileMapper.updateFileTitle(newTitle,sqlNewPath);
        }

    }

    @Override
    public void pasteFile(String oldPath, String newPath) throws InvalidPathException, InvalidNewpathException {
        String username = UserNameUtils.getUsername();
        File file = fileMapper.selectFileByPath(username+"/"+oldPath);
        Folder folder = folderMapper.selectFolderByPath(username+"/"+oldPath);

        String oldPathAll = FolderUtils.basePath+"/" + username + "/" + oldPath;
        String newPathAll = FolderUtils.basePath+"/" + username + "/" + newPath;
        //磁盘上增加新的文件/夹
        if (folder == null) {
            throw new InvalidPathException();
        } else if (file == null) {
            //粘贴文件夹
            folderUtils.pasterFolder(oldPathAll, newPathAll);
        } else {
            //粘贴文件
            folderUtils.pasteFile(oldPathAll, newPathAll);
        }


        //数据库中插入新增的信息
        Folder[] fds = null;
        oldPath=username+"/"+oldPath;
        newPath=username+"/"+newPath;
        fds = folderMapper.selectFolderByPrepath(oldPath);
        if (fds != null) {
            String[] tmps =oldPath.split("/");
            String tmp=tmps[tmps.length-1];
            //父级目录也要做判断，没有存在于数据库中则加上
            String[] tmps2=newPath.split("/");
            String tmp2="";
            for(int i=0;i<tmps2.length;i++){
                if(i==0){
                    tmp2+=tmps2[i];
                }else{
                    tmp2+="/"+tmps2[i];
                }
                Folder folder2=folderMapper.selectFolderByPath(tmp2);
                if(null == folder2){
                    folder2=new Folder();
                    folder2.setUsername(username);
                    folder2.setPath(tmp2);
                    folderMapper.insertFolder(folder2);
                }
            }
            for (Folder fd : fds) {
                Folder fl;
                File fi;
                fi=fileMapper.selectFileByPath(fd.getPath());
                String fdNewPath = newPath+"/"+tmp;
                String suprePath = fd.getPath().substring(oldPath.length());
                fdNewPath += suprePath;
                fd.setPath(fdNewPath);
                fl=folderMapper.selectFolderByPath(fdNewPath);
                if(null == fl) {
                    //如果新路径下没有这个文件夹则插入
                    folderMapper.insertFolder(fd);
                }
                if(null != fi){
                    //该路径为文件的话，则file表更新
                    fi.setPath(fdNewPath);
                    File tp=new File();
                    tp=fileMapper.selectFileByPath(fdNewPath);
                    if(null == tp){
                        //如果新的路径没有保存在file表中则插入
                        String[] names =fdNewPath.split("\\.");
                        if(names[names.length - 1].equalsIgnoreCase("jpg") || names[names.length - 1].equalsIgnoreCase("png") || names[names.length - 1].equalsIgnoreCase("jpeg")){
                            fi.setPicturePath1(fdNewPath);
                            fileMapper.insertFileWithPic1(fi);
                        }else{
                            fileMapper.insertFileWithSum(fi);
                        }

                    }else{
                        //如果新路径已经在file表中存在，则更新
                        String[] names =fdNewPath.split("\\.");
                        if(names[names.length - 1].equalsIgnoreCase("jpg") || names[names.length - 1].equalsIgnoreCase("png") || names[names.length - 1].equalsIgnoreCase("jpeg")){
                            fi.setPicturePath1(fdNewPath);
                            fileMapper.updateFileWithPic1(fi);
                        }else{
                            fileMapper.updateFileWithSummary(fi);
                        }
                        updateFileLastTime(fdNewPath);
                    }
                }
            }
        }
    }

    /**
     * 保存普通笔记（包括修改覆盖）
     * @param path 文件路径（如果是修改，则是文件旧路径）
     * @param title 笔记的标题 （如果是修改标题，则这里与path的最后不同）
     * @param file 笔记文字文件
     * @param pics 笔记图片文件
     * @param summary 文件摘要，如果没有，则为空字符串
     * @throws Exception 异常处理
     */
    @Override
    public void saveFileWithWord(String path, String title, MultipartFile file,ArrayList<MultipartFile>pics,String summary) throws Exception {
        String username = UserNameUtils.getUsername();
        Folder oldFd=folderMapper.selectFolderByPath(username+"/"+path);

        String basePath = FolderUtils.basePath+"/"+ username;
        StringBuilder parentPath= new StringBuilder();
        String[] dirs = path.split("/");
        for(int i=0;i<dirs.length-1;i++){
            if(i==0){
                parentPath.append(dirs[i]);
            }else{
                parentPath.append("/");
                parentPath.append(dirs[i]);
            }
        }
        //对传入参数进行合理性判断(原路径不存在时，即新建，标题要和path末尾一致)
        if(oldFd==null && !title.endsWith(dirs[dirs.length-1])){
            throw new InvalidPathException();
        }
        if(oldFd!=null){
            //如果旧路径存在，则是修改笔记,需在服务器上先删除原来的文件目录和图片文件夹
            folderUtils.deleteFile(basePath+"/"+path);
            String picPath=FolderUtils.picture+parentPath.substring(FolderUtils.file.length())+"/"+dirs[dirs.length-1].split("\\.")[0];
            folderUtils.deleteFolder(basePath+"/"+picPath);
        }
        //将文件放在我的文件夹目录下
        folderUtils.uploadFile(basePath, parentPath.toString(),title,file);
        List<String> picUrls=new ArrayList<>();
       // folderUtils.uploadFile(basePath, parentPath.toString(), title, file);
        //未压缩图片
//        if(pics.size()>0){
//            //如果该文件中还有图片,则将图片对应存到图片目录下
//            String[] titles;
//            titles = title.split("\\.");
//            String halftitle=titles[0];
//            for(int i=0;i<pics.size();i++){
//                String picParent=FolderUtils.picture+parentPath.substring(FolderUtils.file.length())+"/"+halftitle;
//                String filename=pics.get(i).getOriginalFilename();
//                folderUtils.uploadFile(basePath,picParent,filename,pics.get(i));
//                if(i>=(pics.size()-3)){
//                    picUrls.add(username+"/"+picParent+"/"+filename);
//                }
//            }
//        }
        //压缩图片
        if(pics.size()>0){
            //如果该文件中还有图片,则将图片对应存到图片目录下
            String[] titles;
            titles = title.split("\\.");
            String halftitle=titles[0];
            for(int i=0;i<pics.size();i++){
                String picParent=FolderUtils.picture+parentPath.substring(FolderUtils.file.length())+"/"+halftitle;
                String filename=pics.get(i).getOriginalFilename();
                java.io.File compressFile=compressImg.getCompressPath(pics.get(i));
                //java.io.File tmpImg=new  java.io.File(compressPath);
                //folderUtils.uploadFile(basePath,picParent,filename,pics.get(i));
                folderUtils.uploadRealFile(basePath,picParent,filename,compressFile);
                if(i>=(pics.size()-3)){
                    picUrls.add(username+"/"+picParent+"/"+filename);
                }
            }
        }
        //在数据库中插入文件的内容

        //如果笔记不在数据库中则插入新的记录,没有的话就覆盖
        String sqlOldPath=username+"/"+path;
        String sqlNewPath=username+"/"+parentPath+"/"+title;

        if (oldFd == null) {
            assert false;
            String[] tmps=sqlOldPath.split("/");
            String tmp=tmps[0];
            //该路径下每个目录都要判断是否存在，不存在则添加
            for(int i=1;i<tmps.length;i++){
                tmp+="/";
                tmp+=tmps[i];
                Folder folder = null;
                folder=new Folder();
                if(folderMapper.selectFolderByPath(tmp)==null){
                    folder.setPath(tmp);
                    folder.setUsername(username);
                    folderMapper.insertFolder(folder);
                }
            }
        }else{
            //folderMapper.updateFolderPath(sqlOldPath,sqlNewPath,sqlOldPath.length()+1);
            folderMapper.updateFolderOnlyPath(sqlOldPath,sqlNewPath);
        }
        saveNoteToMysql(sqlNewPath,file,title,picUrls,summary);
    }

    @Override
    public String getFilePath(String path) throws InvalidPathException {
        path=UserNameUtils.getUsername()+"/"+path;
        Folder fd=folderMapper.selectFolderByPath(path);
        if(null == fd){
            throw new InvalidPathException();
        }
        return FolderUtils.IP+"/"+path;
    }

    @Override
    public void importWord(String path, MultipartFile file) throws Exception {
        //将word文件上传到服务器
        String filename=file.getOriginalFilename();
        java.io.File toFile= FolderUtils.multipartFileToFile(file);
        assert filename != null;
        if(!filename.endsWith(".docx") && !filename.endsWith(".doc")){
            throw new InvalidPathException();
        }else{
            String htmlFileName=filename.split("\\.")[0]+".txt";
            java.io.File htmlFile=null;
            String summary="";
            ArrayList<java.io.File> picList=null;
            if(filename.endsWith(".docx")){
                //将docx文件转为html文件
                String htmlPath=word2HtmlUtils.docx2html(toFile);
                htmlFile=new java.io.File(htmlPath);
                //htmlFileName=filename.split("\\.")[0]+".html";

                //提取文件中的摘要,至多截取前20个字符作为摘要
                String result=word2HtmlUtils.collectTextFromDocx(toFile);
                summary=result.length()>20?result.substring(0,21):result;
                //提取文件中的图片，至多提取三张
                picList=word2HtmlUtils.collectPicsFromDocx(toFile);
            }else{
                //将doc文件转为html文件
                String htmlPath=word2HtmlUtils.doc2html(toFile);
                htmlFile=new java.io.File(htmlPath);
                //htmlFileName=filename.split("\\.")[0]+".html";

                //提取文件中的摘要,至多截取前20个字符作为摘要
                String result=word2HtmlUtils.collectTextFromDoc(toFile);
                summary=result.length()>20?result.substring(0,21):result;
                //提取图片
                picList=word2HtmlUtils.collectPicsFromDoc(toFile);
            }
            //将html上传到服务器
            folderUtils.uploadRealFile(FolderUtils.basePath+"/"+UserNameUtils.getUsername(),path,htmlFileName,htmlFile);
            String databasePath=UserNameUtils.getUsername()+"/"+path+"/"+htmlFileName;
            String[] folderPathes =databasePath.split("/");
            String tmp="";
            //判断所有文件夹是否在数据库中，没有则插入
            for(int i=0;i<folderPathes.length;i++){
                if(i==0){
                    tmp+=folderPathes[i];
                }else{
                    tmp+="/"+folderPathes[i];
                }
                Folder fd=folderMapper.selectFolderByPath(tmp);
                if(fd==null){
                    //如果数据库中不存在该word文件，则插入
                    fd=new Folder();
                    fd.setPath(tmp);
                    fd.setUsername(UserNameUtils.getUsername());
                    folderMapper.insertFolder(fd);
                }
            }
            File newFile=new File();
            newFile.setPath(databasePath);
            //存储文件大小
            String size=Long.toString(htmlFile.length());
            newFile.setSize(size);
            //存储文件标题
            newFile.setTitle(htmlFileName);
            //提取文件中的摘要,至多截取前20个字符作为摘要
            newFile.setSummary(summary);
            //提取文件中的图片，至多提取三张
            String basePath=FolderUtils.basePath+"/"+UserNameUtils.getUsername()+"/"+FolderUtils.picture;
            String parenPath=path.substring(FolderUtils.file.length()+1,path.length())+"/"+filename.split("\\.")[0];
            for(int i=0;i<picList.size();i++){
                String picname=picList.get(i).getName();
                folderUtils.uploadRealFile(basePath,parenPath,picname,picList.get(i));
                if(i==0){
                    newFile.setPicturePath1(UserNameUtils.getUsername()+"/"+FolderUtils.picture+"/"+parenPath+"/"+picname);
                }else if(i==1){
                    newFile.setPicturePath2(UserNameUtils.getUsername()+"/"+FolderUtils.picture+"/"+parenPath+"/"+picname);
                }else if(i==2){
                    newFile.setPicturePath3(UserNameUtils.getUsername()+"/"+FolderUtils.picture+"/"+parenPath+"/"+picname);
                }
            }
            File fl=fileMapper.selectFileByPath(databasePath);
            if(fl==null){
                //如果文件表中没有该word文件，则插入
                fileMapper.insertNote(newFile);
            }else{
                //如果文件表中有该word文件，则覆盖
                fileMapper.updatetNote(newFile);
                updateFileLastTime(databasePath);
            }
        }




    }




    @Override
    public String exportWord(String path) throws SftpException, IOException, DocumentException, InvalidPathException {
        String sqlPath=UserNameUtils.getUsername()+"/"+path;
        Folder folder=folderMapper.selectFolderByPath(sqlPath);
        if(folder==null){
            throw new InvalidPathException();
        }
        String remotePath=FolderUtils.basePath+"/"+UserNameUtils.getUsername()+"/"+path;
        String localPath=this.getClass().getResource("/").getPath()+"static/file/tmp.txt";
        folderUtils.downloadFile(remotePath,localPath);
        java.io.File file=new java.io.File(localPath);
        String content=html2WordUtils.readFile(file);
       // String targetFileName=html2WordUtils.html2word(request,response,content);
        String targetFileName=html2WordUtils.ItextCreatRTF(content);
        String filename=path.split("/")[path.split("/").length-1].split("\\.")[0]+".doc";
        //在tmp临时文件目录下放导出的doc文件
        folderUtils.uploadRealFile(FolderUtils.basePath+"/"+UserNameUtils.getUsername(),"tmp",filename,new java.io.File(targetFileName));
        return FolderUtils.IP+"/"+UserNameUtils.getUsername()+"/"+"tmp/"+filename;
    }

    @Override
    public String md2pdf(String path) throws FileNotFoundException, SftpException, UnsupportedEncodingException, InvalidPathException {
        String sqlPath=UserNameUtils.getUsername()+"/"+path;
        Folder folder=folderMapper.selectFolderByPath(sqlPath);
        if(folder==null){
            throw new InvalidPathException();
        }
        String remotePath=FolderUtils.basePath+"/"+UserNameUtils.getUsername()+"/"+path;
        String localPath=this.getClass().getResource("/").getPath()+"static/file/tmp.md";
        folderUtils.downloadFile(remotePath,localPath);
        java.io.File mdfile=new java.io.File(localPath);
        String pdfPath=this.getClass().getResource("/").getPath()+"static/pdf/tmp.pdf";
        md2pdfUtils.md2pdf(mdfile,pdfPath);
        String filename=path.split("/")[path.split("/").length-1].split("\\.")[0]+".pdf";
        folderUtils.uploadRealFile(FolderUtils.basePath+"/"+UserNameUtils.getUsername(),"tmp",filename,new java.io.File(pdfPath));
        return FolderUtils.IP+"/"+UserNameUtils.getUsername()+"/"+"tmp/"+filename;
    }


    private void saveNoteToMysql(String newpath, MultipartFile file, String title,List<String> picUrls,String summary) throws Exception {
        File fl=new File();
        fl.setPath(newpath);
        String size= String.valueOf(file.getSize());
        fl.setSize(size);
        fl.setTitle(title);
        //从文件中读出至多三行为文件的摘要
//        java.io.File toFile= FolderUtils.multipartFileToFile(file);
//        FileReader reader = new FileReader(toFile);
//        BufferedReader br = new BufferedReader(reader);
//        String line="";
//        StringBuilder summary= new StringBuilder();
//        int flag=0;//用于记录摘要的长度，最多不超过原来文件的三行
//        while ((line = br.readLine()) != null) {
//            // 一次读入一行数据
//            summary.append(line);
//            flag++;
//            if(flag>=3)
//                break;
//        }
        fl.setSummary(summary);
        //将图片的映射存入数据库
        for(int i=0;i<picUrls.size();i++){
            if(i==0){
                fl.setPicturePath1(picUrls.get(i));
            }else if(i==1){
                fl.setPicturePath2(picUrls.get(i));
            }else if(i==2){
                fl.setPicturePath3(picUrls.get(i));
            }
        }
        File fi=null;
        fi=fileMapper.selectFileByPath(newpath);
        if(fi==null){
            //如果文件不存在于数据库则插入
            fileMapper.insertNote(fl);
        }else {
            //如果文件存在，则更新;更新的话则上次更新时间也更新
            fileMapper.updatetNote(fl);
            updateFileLastTime(newpath);
        }
    }
    /**
     * 将图片/文件加入/更新到数据库
     * @param path 文件路径
     * @param file 文件
     * @param title 文件标题
     * @param type 插入/更新
     * @throws Exception 异常
     */
    private void saveFileToMysql(String path, MultipartFile file, String title,String type) throws Exception {
        File myfile = new File();
        myfile.setPath(path);
        myfile.setTitle(title);
        String size = String.valueOf(file.getSize());
        myfile.setSize(size);


        //判断是文件还是图片
        String[] names = title.split("\\.");
        if (names[names.length - 1].equalsIgnoreCase("jpg") || names[names.length - 1].equalsIgnoreCase("png") || names[names.length - 1].equalsIgnoreCase("jpeg")) {
            //是图片则保存路径，这里的路径即为他的path
            myfile.setPicturePath1(path);
            if(type.equals("insert")){
                fileMapper.insertFileWithPic1(myfile);
            }else if(type.equals("update")){
                fileMapper.updateFileWithPic1(myfile);
                //文件更新时候时间也更新
                updateFileLastTime(path);
            }

        } else {
            //从文件中读出至多三行为文件的摘要
            java.io.File toFile = FolderUtils.multipartFileToFile(file);
            FileReader reader = new FileReader(toFile);
            BufferedReader br = new BufferedReader(reader);
            String line = "";
            StringBuilder summary = new StringBuilder();
            int flag = 0;//用于记录摘要的长度，最多不超过原来文件的三行
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                summary.append(line);
                flag++;
                if (flag >= 3)
                    break;
            }
            myfile.setSummary(summary.toString());
            if(type.equals("insert")){
                fileMapper.insertFileWithSum(myfile);
            }else if(type.equals("update")){
                fileMapper.updateFileWithSummary(myfile);
                //文件更新时候时间也更新
                updateFileLastTime(path);
            }

        }



    }
    @Override
    public void editFile(String path, String author, String origin) throws InvalidPathException{
        path=UserNameUtils.getUsername()+"/"+path;
        File file=fileMapper.selectFileByPath(path);
        int res=0;
        if(file==null){
            throw new InvalidPathException();
        }else{
            file.setAuthor(author);
            file.setOrigin(origin);
            res=fileMapper.updateFileWithAuthor(file);
            if(res<=0){
                throw new BusyException();
            }
        }
    }

}
